<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Prompt 优化</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-plus/dist/index.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
    <script src="https://cdn.jsdelivr.net/npm/element-plus"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .container {
            max-width: 1600px;
            margin: 0 auto;
            padding: 60px 40px;
            background-color: #f5f7fa;
            min-height: 100vh;
            box-sizing: border-box;
        }
        .header {
            text-align: center;
            margin-bottom: 60px;
            color: #303133;
        }
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 16px;
            font-weight: 600;
        }
        .header p {
            font-size: 1.2em;
            color: #606266;
        }
        .prompt-form {
            background: white;
            padding: 48px;
            border-radius: 12px;
            box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
        }
        .button-container {
            display: flex;
            justify-content: center;
            margin: 48px 0;
            gap: 16px;
        }
        .el-button--primary {
            padding: 12px 24px;
            font-size: 16px;
        }
        .el-input__inner,
        .el-textarea__inner {
            background-color: #f8f9fb;
        }
        .el-form-item__label {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
            padding-bottom: 8px;
        }
        .el-form-item {
            margin-bottom: 32px;
        }
        .el-collapse {
            border: none;
            margin-top: 20px;
        }
        .el-collapse-item__header {
            font-size: 14px;
            color: #606266;
        }
        .error-alert {
            margin-bottom: 20px;
        }
        .api-key-error {
            margin-top: 16px;
            padding: 12px;
            border-radius: 4px;
            background-color: #fef0f0;
            color: #f56c6c;
            font-size: 14px;
            line-height: 1.5;
        }
        .api-key-error .el-button {
            margin-left: 8px;
            margin-top: 8px;
        }
        .error-alert .el-alert__title {
            font-size: 14px;
            line-height: 1.5;
            white-space: pre-line;
        }
    </style>
</head>
<body>
    <div id="app" class="container">
        <div class="header">
            <h1>欢迎使用 Prompt 优化</h1>
            <p>将简短的任务描述优化成结构完整的 Prompt</p>
        </div>
        
        <el-form class="prompt-form" @submit.prevent="generatePrompt" :model="form" :rules="rules">
            <el-alert
                v-if="error"
                :title="error"
                type="error"
                class="error-alert"
                show-icon
                :closable="true"
                @close="clearError"
                :description="errorDescription"
            >
                <template v-if="isApiKeyError">
                    <div class="api-key-error">
                        <p>您可以通过以下方式配置 API Key：</p>
                        <p>1. 在高级设置中输入 API Key</p>
                        <p>2. 或在系统配置文件中设置默认的 API Key</p>
                        <el-button type="primary" size="small" @click="showAdvancedSettings">
                            打开高级设置
                        </el-button>
                    </div>
                </template>
            </el-alert>
            
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="原始Prompt" label-position="top" prop="taskDescription">
                        <el-input
                            v-model="form.taskDescription"
                            type="textarea"
                            :rows="16"
                            placeholder="请输入原始Prompt"
                            clearable
                        ></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="优化后的Prompt" label-position="top">
                        <el-input
                            v-model="generatedPrompt"
                            type="textarea"
                            :rows="16"
                            readonly
                        ></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <div class="button-container">
                <el-button @click="clearForm">清空内容</el-button>
                <el-button type="primary" @click="generatePrompt">生成 Prompt</el-button>
            </div>
            
            <el-collapse v-model="activeCollapse">
                <el-collapse-item title="高级设置" name="advanced">
                    <el-form-item label="模型选择" label-position="right">
                        <el-select v-model="form.model" placeholder="请选择模型">
                           <el-option label="GPT-4o-mini" value="gpt-4o-mini"></el-option>
                            <el-option label="GPT-4o" value="gpt-4o"></el-option>
                            <el-option label="GPT-4" value="gpt-4"></el-option>
                            <el-option label="DeepSeek-V3" value="deepseek-v3"></el-option>
                            <el-option label="DeepSeek-R1" value="deepseek-r1"></el-option>
                            <el-option label="Claude-3.5-Sonnet" value="claude-3-5-sonnet-20241022"></el-option>
                            <el-option label="Claude-3.7-Sonnet" value="claude-3-7-sonnet-20250219"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="API Key" prop="apiKey" label-position="right">
                        <el-input v-model="form.apiKey" placeholder="请输入 API Key"></el-input>
                    </el-form-item>
                </el-collapse-item>
            </el-collapse>
        </el-form>
    </div>

    <script>
        const { createApp, ref, reactive } = Vue

        createApp({
            setup() {
                const form = reactive({
                    taskDescription: '',
                    apiKey: '',
                    model: 'gpt-4o-mini'
                })
                const generatedPrompt = ref('')
                const error = ref('')
                const errorDescription = ref('')
                const isApiKeyError = ref(false)
                const activeCollapse = ref([])

                const rules = {
                    taskDescription: [{
                        required: true,
                        message: '请输入原始Prompt内容',
                        trigger: 'blur'
                    }],
                    apiKey: [{
                        required: true,
                        message: '请输入 API Key',
                        trigger: ['blur', 'change']
                    }]
                }

                const showAdvancedSettings = () => {
                    activeCollapse.value = ['advanced']
                }

                const clearError = () => {
                    error.value = ''
                    errorDescription.value = ''
                    isApiKeyError.value = false
                }

                const generatePrompt = async () => {
                    try {
                        clearError()
                        
                        // 先检查 API Key
                        if (!form.apiKey.trim()) {
                            isApiKeyError.value = true
                            showAdvancedSettings()
                            ElMessage({
                                message: '请先配置 API Key 后再生成 Prompt',
                                type: 'warning',
                                duration: 3000,
                                showClose: true
                            })
                            return
                        }

                        // 验证表单
                        const formEl = document.querySelector('.prompt-form')
                        const valid = await formEl.__vueParentComponent.exposed.validate()
                            .catch(error => {
                                // 处理其他验证错误
                                if (error.fields) {
                                    const errorMsg = Object.values(error.fields)[0]?.[0]?.message
                                    if (errorMsg) {
                                        ElMessage.warning(errorMsg)
                                    }
                                }
                                return false
                            })

                        if (!valid) {
                            return
                        }

                        if (!form.taskDescription.trim()) {
                            ElMessage.warning('请输入原始Prompt内容');
                            return;
                        }

                        const url = '/api/prompt/optimize'
                        
                        const requestData = {
                            taskDescription: form.taskDescription,
                            apiKey: form.apiKey,
                            model: form.model
                        }

                        const response = await axios.post(url, requestData)
                        if (response.data && response.data.prompt) {
                            generatedPrompt.value = response.data.prompt
                            ElMessage.success('生成成功');
                        } else {
                            throw new Error('Response does not contain prompt field')
                        }
                    } catch (error) {
                        console.error('Error details:', error.response || error)
                        let errorMessage = '生成失败，请稍后重试'
                        let description = ''
                        
                        if (error.response?.data) {
                            if (error.response.data.message) {
                                errorMessage = error.response.data.message
                                // 显示错误消息提示
                                ElMessage({
                                    message: errorMessage,
                                    type: 'error',
                                    duration: 5000,
                                    showClose: true
                                })
                            }
                            if (error.response.data.details) {
                                description = error.response.data.details.join('\n')
                            }
                        } else if (error.message) {
                            errorMessage = error.message
                            // 显示错误消息提示
                            ElMessage({
                                message: errorMessage,
                                type: 'error',
                                duration: 5000,
                                showClose: true
                            })
                        }
                        
                        // 检查是否是API Key相关的错误
                        if (errorMessage.includes('API Key')) {
                            isApiKeyError.value = true
                            showAdvancedSettings()
                        }
                        
                        error.value = errorMessage
                        errorDescription.value = description
                    }
                }

                const clearForm = () => {
                    form.taskDescription = ''
                    generatedPrompt.value = ''
                    clearError()
                }

                return {
                    form,
                    rules,
                    error,
                    errorDescription,
                    isApiKeyError,
                    activeCollapse,
                    generatedPrompt,
                    generatePrompt,
                    clearForm,
                    clearError,
                    showAdvancedSettings
                }
            }
        }).use(ElementPlus).mount('#app')
    </script>
</body>
</html>